package com.shop.cloud.common.getui.utils;

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.api.UserApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.AudienceDTO;
import com.getui.push.v2.sdk.dto.req.CidAliasListDTO;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.shop.cloud.common.getui.config.GeTuiProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 个推工具类
 * https://github.com/GetuiLaboratory/getui-pushapi-java-client-v2
 * @author
 * @date 2022-08-12 16:25:10
 */
@Slf4j
@Component
@AllArgsConstructor
public class GeTuiUtil {

    private final GeTuiProperties geTuiProperties;

    /**
     * 创建消息体
     * @param pushDTO
     * @return
     */
    public ApiResult createMsg(PushDTO<Audience> pushDTO){
        PushApi pushApi = this.getApiHelper().creatApi(PushApi.class);
        return pushApi.createMsg(pushDTO);
    }

    /**
     * 根据别名推送
     * @param pushDTO
     * @return
     */
    public ApiResult pushByAlias(PushDTO<Audience> pushDTO){
        PushApi pushApi = this.getApiHelper().creatApi(PushApi.class);
        return pushApi.pushToSingleByAlias(pushDTO);
    }

    /**
     * 根据别名批量推送
     * 对列表中所有别名进行消息推送。调用此接口前需调用创建消息接口设置消息内容。
     * @param audienceDTO
     * @return
     */
    public ApiResult pushListByAlias(AudienceDTO audienceDTO){
        PushApi pushApi = this.getApiHelper().creatApi(PushApi.class);
        return pushApi.pushListByAlias(audienceDTO);
    }

    /**
     * 根据cid查询别名
     * @param cid
     */
    public ApiResult queryAliasByCid(String cid){
        UserApi userApi = this.getApiHelper().creatApi(UserApi.class);
        return userApi.queryAliasByCid(cid);
    }

    /**
     * 绑定别名
     * @param cidAliasListDTO
     * @return
     */
    public ApiResult bindAlias(CidAliasListDTO cidAliasListDTO){
        UserApi userApi = this.getApiHelper().creatApi(UserApi.class);
        return userApi.bindAlias(cidAliasListDTO);
    }

    /**
     * 实例化ApiHelper对象，用于创建接口对象
     * @return
     */
    private ApiHelper getApiHelper(){
        // 设置httpClient最大连接数，当并发较大时建议调大此参数。或者启动参数加上 -Dhttp.maxConnections=200
        System.setProperty("http.maxConnections", "200");
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置
        apiConfiguration.setAppId(geTuiProperties.getAppId());
        apiConfiguration.setAppKey(geTuiProperties.getAppKey());
        apiConfiguration.setMasterSecret(geTuiProperties.getMasterSecret());
        // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        apiConfiguration.setDomain(geTuiProperties.getDomain());
        // 实例化ApiHelper对象，用于创建接口对象
        return ApiHelper.build(apiConfiguration);
    }
}
